package com.mercenary.wein.screenControl.command;

import com.mercenary.wein.screenControl.bean.CommandDetailBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by tuxiao on 2017/3/11.
 */
public class CommandSocketClient {
    private Log log = LogFactory.getLog(CommandSocketClient.class);
    private Socket client;
    private DataInputStream in;
    private PrintWriter out;

    public CommandSocketClient(String ip, int port) throws IOException {
        client = new Socket(ip, port);
        in = new DataInputStream(client.getInputStream());
        out = new PrintWriter(client.getOutputStream());
    }

    public String command(String command) throws IOException, InterruptedException {
        log.info("send command:" + command);
        out.print(command);
        out.flush();
        new Thread() {
            public void run() {
                //发送指令后，约定好发送I'm waiting for u 用以保持连接，服务端一次流程比较耗时，在手机操作结束后，会返回信息。接收到消息后，关闭连接即可。
                for (int j = 0; j < 100; j++) {
                    try {
                        sleep(4000);
                        out.print("I'm waiting for u");
                        out.flush();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                    }
                }
            }
        }.start();
        String answer;
        byte[] buffer;
        for (int j = 0; j < 400; j++) {
            //创建一个流套接字并将其连接到指定主机上的指定端口号
            //读取服务器端数据
            Thread.sleep(1000);
            buffer = new byte[in.available()];
            if (buffer.length != 0) {
                // 读取缓冲区
                in.read(buffer);
                // 转换字符串
                answer = new String(buffer);
                log.info("answer=" + answer);
                return answer;
            }
        }
        return null;
    }

    public void close() {
        try {
            in.close();
            out.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
